/* eslint-disable no-warning-comments */
/* eslint-disable import/no-extraneous-dependencies */
"use strict";

const {
  Worker,
  isMainThread,
  parentPort,
  workerData,
} = require("node:worker_threads");

if (isMainThread) {
  /**
   * @param {string} script
   * @returns {Promise<import("acorn").Node>}
   */
  module.exports = function parseJSAsync(script) {
    return new Promise((resolve, reject) => {
      const worker = new Worker(__filename, {
        workerData: script,
      });
      worker.on("message", resolve);
      worker.on("error", reject);
      worker.on("exit", (code) => {
        if (code !== 0) {
          reject(new Error(`Worker stopped with exit code ${code}`));
        }
      });
    });
  };
} else {
  const { parse } = require("acorn");

  const script = workerData;
  // @ts-ignore - actual is fine
  parentPort?.postMessage(parse(script));
}
